package com.healthcloud.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.healthcloud.constants.PagineConsts;
import com.healthcloud.entity.SysMenuEntity;
import com.healthcloud.entity.SysUserEntity;
import com.healthcloud.service.SysMenuService;
import com.healthcloud.service.SysUserService;
import com.healthcloud.utils.*;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录相关
 * Created by yu on 2017/6/6.
 */
@ApiIgnore
@Controller
public class SysLoginController extends AbstractController{


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/login",method= RequestMethod.GET)
    public Object doLoginGet(Model model, HttpServletRequest request) {

        //todo
        //读取医院名称
    	Cookie cookies[]=request.getCookies(); //读出用户硬盘上的Cookie，并将所有的Cookie放到一个cookie对象数组里面
    	if (cookies!=null) {
        	Cookie sCookie=null;
        	for(int i=0;i<cookies.length-1;i++){    //用一个循环语句遍历刚才建立的Cookie对象数组
        	sCookie=cookies[i];   //取出数组中的一个Cookie对象
        	if(sCookie!=null){
        	      if(("hospShortName").equals(sCookie.getName())){
        	    	  try {
						model.addAttribute("hospShortName",URLDecoder.decode(sCookie.getValue(),"utf-8"));
					} catch (UnsupportedEncodingException e) {
                          logger.error(e.getMessage());
					}
        	      }
        		}
        	}
		}
        return "login";
    }


    /**
     * 登录页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/dwlogin",method= RequestMethod.GET)
    public Object doNewLoginGet(Model model, HttpServletRequest request) {

        //todo
        //读取医院名称
        Cookie cookies[]=request.getCookies(); //读出用户硬盘上的Cookie，并将所有的Cookie放到一个cookie对象数组里面
        if (cookies!=null) {
            Cookie sCookie=null;
            for(int i=0;i<cookies.length-1;i++){    //用一个循环语句遍历刚才建立的Cookie对象数组
                sCookie=cookies[i];   //取出数组中的一个Cookie对象
                if(sCookie!=null){
                    if(("hospShortName").equals(sCookie.getName())){
                        try {
                            model.addAttribute("hospShortName",URLDecoder.decode(sCookie.getValue(),"utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            logger.error(e.getMessage());
                        }
                    }
                }
            }
        }
        return "dwlogin";
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object doLoginPost(String username,String password,Model model,HttpServletRequest request) throws IOException,Exception{

        try{

            password = AESUtil.aesDecrypt(password,"anUqKhuAQzVYLnhT");
            Subject subject = ShiroUtils.getSubject();
            password = new EncryptionUtils().encryptionMd5(password);
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);

        }catch (UnknownAccountException e) {
            logger.error(e.getMessage());
            model.addAttribute("errorMsg",e.getMessage());
            return "login";
        }catch (IncorrectCredentialsException e) {
            logger.error(e.getMessage());
            model.addAttribute("errorMsg",e.getMessage());
            return "login";
        }catch (LockedAccountException e) {
            logger.error(e.getMessage());
            model.addAttribute("errorMsg",e.getMessage());
            return "login";
        }catch (AuthenticationException e) {
            logger.error(e.getMessage());
            model.addAttribute("errorMsg","账户验证失败");
            return "login";
        }


        model.addAttribute("userId",ShiroUtils.getUserId());


        //查询列表数据
        List<SysMenuEntity> menuList = null;
        //只有超级管理员，才能查看所有管理员列表
        if (getUser().getUsername().equals(Constant.ADMIN)) {
            PageParam pageParam = new PageParam();
            pageParam.setiDisplayStart(PagineConsts.iDisplayStart);
            pageParam.setiDisplayLength(PagineConsts.iDisplayLength);
            menuList = sysMenuService.queryList(new SysMenuEntity(), pageParam);
        } else {
            menuList = sysMenuService.queryUserList(getUserId());
        }

        model.addAttribute("menuList",menuList);

        return "index";
    }

    /**
     * 首页
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public Object showIndex(@RequestParam(name = "accessToken",required = false) String accessToken,Model model) throws Exception{

        if(StringUtils.isBlank(accessToken)){
            return "login";
        }

        String userInfo = UrlClient.getService(accessToken);

        Gson gson = new GsonBuilder().create();
        SysUserEntity user = gson.fromJson(userInfo,SysUserEntity.class);
        user = sysUserService.queryByUserName(user.getUsername());
        Subject subject = ShiroUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        subject.login(token);



        model.addAttribute("userId",ShiroUtils.getUserId());

        //查询列表数据
        List<SysMenuEntity> menuList = null;
        //只有超级管理员，才能查看所有管理员列表
        if (getUser().getUsername().equals(Constant.ADMIN)) {
            PageParam pageParam = new PageParam();
            pageParam.setiDisplayStart(PagineConsts.iDisplayStart);
            pageParam.setiDisplayLength(PagineConsts.iDisplayLength);
            menuList = sysMenuService.queryList(new SysMenuEntity(), pageParam);
        } else {
            menuList = sysMenuService.queryUserList(getUserId());
        }

        model.addAttribute("menuList",menuList);
        return "index";
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login";
    }

}
